//
//  BaseViewController.m
//  BeiBei
//
//  Created by apple on 16/7/28.
//  Copyright © 2016年 XiaoYu. All rights reserved.
//

#import "BaseViewController.h"

@interface BaseViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    float _titleScrollViewWidth;//记录全部标题的最大值
    UIView * _lineLabel;//用来确定but与下划线相互位置
//    float _previousPosition;废步！
    int _btnIndex;//记录but的tag值 用来判定是否在点击but时改变其颜色
    UIScrollView * _contentScrollView;//内容滑动视图 当作bj容纳内容
    UICollectionView * _bgCollectionView;//创建集合视图 来容纳内容
    UIScrollView * _topScrollView;//创建滑动视图
    UIPageControl * _pageControl;//创建滑动视图页脚
    NSTimer * _timer;//创建定时器
    NSArray * _array;
}
@property (weak, nonatomic) IBOutlet UIView *bgView;
@end

@implementation BaseViewController


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

//    self.view.backgroundColor = [UIColor yellowColor];
    
}


#pragma mark----创建一个NavBar
-(void)addView:(UIView *)view leftBut:(NSString * )imageNamed rightBut:(NSString * )imageNamed2 titleView:(NSString *)imageNamed3 dataArray:(NSArray *)titleArray
{
//    float WindowWidth= WINDOW.frame.size.width;
    
    UIView * bgView = [[UIView alloc] init];
    bgView.frame = CGRectMake(0, 20, Window_Width, 80);
//    bgView.backgroundColor = [UIColor redColor];
    [view addSubview:bgView];
    
    UIButton * leftBut = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBut.frame = CGRectMake(10, 5, 35, 35);
    [leftBut setImage:[UIImage imageNamed:imageNamed] forState:UIControlStateNormal];
//    leftBut.tintColor = [UIColor redColor];
    [leftBut addTarget:self action:@selector(addLeftBut) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:leftBut];
    
    UIButton * rightBut = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBut.frame = CGRectMake(Window_Width-45, 5, 35, 35);
    [rightBut setImage:[UIImage imageNamed:imageNamed2] forState:UIControlStateNormal];
    //    leftBut.tintColor = [UIColor redColor];
    [rightBut addTarget:self action:@selector(addRightBut) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:rightBut];
    
    UIImageView * titleView = [[UIImageView alloc] init];
    titleView.image = [UIImage imageNamed:imageNamed3];
    float titleViewWidth =Window_Width/3;
    titleView.frame = CGRectMake(Window_Width/3+10, 5, titleViewWidth-20, 35);
    [bgView addSubview:titleView];
    
    
    
    
    UIScrollView * titleScrollView = [[UIScrollView alloc] init];
    titleScrollView.frame = CGRectMake(0, 50, Window_Width, 30);
//    titleScrollView.backgroundColor = [UIColor blueColor];
    
//    NSArray * array = @[@"上新",@"童装",@"童鞋",@"用品玩具",@"女装",@"鞋包",@"居家",@"美妆",@"美食",@"最后疯抢",@"下期预告"];
    /*
     用sumLength 表示每一个button的起点x坐标；
     假设第一个button的起点x坐标为20，sumLength=20 ，
     那么 sumLength += 第一个button的宽度以及间距 表示第二个button的起点；
     */
    float sumLength = 23;
    for (int i = 0; i < titleArray.count; i ++)
    {
//        NSLog(@"%lu",(unsigned long)titleArray.count);
        UIButton * titBut = [UIButton buttonWithType:UIButtonTypeCustom];
        [titBut setTitle:titleArray[i] forState:UIControlStateNormal];
        titBut.titleLabel.font =[UIFont systemFontOfSize:15];
        
        CGSize size = [titBut.titleLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObject:titBut.titleLabel.font forKey:NSFontAttributeName]];
        float width = size.width;
        titBut.frame = CGRectMake(sumLength, 0, width, 28);
        sumLength += width + 23;
        
        
//        每一个button设置normal和selected图片，每个button的点击事件中，当前button设置为isSelected为yes，其他button为NO
        [titBut setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
//        [titBut setBackgroundColor:[UIColor yellowColor]];
        [titBut setTag:i+1];
//        titBut.showsTouchWhenHighlighted = YES;//高亮模式
        [titBut addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleScrollView addSubview:titBut];
        
        _titleScrollViewWidth = sumLength;
        
        if (i == 0)
        {
            _btnIndex = (int)titBut.tag;
            titBut.selected = YES;
            [titBut setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            
//            _previousPosition = titBut.center.x;废步！
            _lineLabel = [[UIView alloc]init];
            _lineLabel.center = CGPointMake(titBut.center.x, 28);
            
            //根据 字的多少、字体的大小 计算字符串的长度
            
            _lineLabel.bounds = CGRectMake(0, 0,width , 2);
            _lineLabel.backgroundColor = [UIColor redColor];
            [titleScrollView addSubview:_lineLabel];
        }
    }
    titleScrollView.contentSize = CGSizeMake(_titleScrollViewWidth, 30);
    titleScrollView.showsHorizontalScrollIndicator = NO;
    titleScrollView.pagingEnabled = NO;
    [bgView addSubview:titleScrollView];
}

-(void)addLeftBut
{
    NSLog(@"左按键");
}

-(void)addRightBut
{
    NSLog(@"右按键");
}

-(void)buttonClick:(UIButton *)button
{
    NSLog(@"点击了标题%ld",(long)button.tag);
    
    UIButton *btn1 = (UIButton *)[self.view viewWithTag:_btnIndex];
    if (_btnIndex != 0)
    {
        btn1.selected = NO;
    }
    UIButton *button1 = (UIButton *)[self.view viewWithTag:[button tag]];
    
    _btnIndex = (int)button1.tag;
    button.selected = YES;
    [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    [UIView animateWithDuration:1 animations:^
     {
         _lineLabel.center = CGPointMake(button.center.x, 28);
         CGSize size  = [button.titleLabel.text sizeWithAttributes: [NSDictionary dictionaryWithObject:button.titleLabel.font forKey:NSFontAttributeName]];
         _lineLabel.bounds = CGRectMake(0, 0, size.width, 2);
         
     }];
}



#pragma mark ---- 创建一个内容UICollectionView总背景

-(void)createBgCollectionView:(UIView *)view
{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.itemSize = CGSizeMake(Window_Width, Window_Height-100-49);
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    
    _bgCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, Window_Width,WINDOW.frame.size.height-100-49 ) collectionViewLayout:layout];
    _bgCollectionView.frame = CGRectMake(0, 100, Window_Width,WINDOW.frame.size.height-100-49 );
    
    _bgCollectionView.backgroundColor = [UIColor purpleColor];
    _bgCollectionView.delegate = self;
    _bgCollectionView.dataSource = self;
    
    [view addSubview:_bgCollectionView];
    
    [_bgCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"bgCell"];
    
    
}


//_bgCollectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 20;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bgCell" forIndexPath:indexPath];
    
    return cell;
}


#pragma mark ---- 创建样式一 1.滑动视图部分

-(void)createsmallScrollView:(NSArray *)smallScrollViewPag
{
    _array = smallScrollViewPag;
    _topScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Window_Width, InterfaceStyleOne_TopScrollView_Height)];
    _topScrollView.contentSize = CGSizeMake(Window_Width*smallScrollViewPag.count, InterfaceStyleOne_TopScrollView_Height);
    for (int i = 0; i<smallScrollViewPag.count; i++)
    {
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(Window_Width*i, 0, Window_Width, InterfaceStyleOne_TopScrollView_Height)];
        
        NSString * str = smallScrollViewPag[i][@"img"];
//        NSString * str =smallScrollViewPag[i];
//        NSLog(@"%@",str);
        imageView.image = [[UIImage alloc]initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]];
//        imageView.backgroundColor = [UIColor redColor];
        [_topScrollView addSubview:imageView];
    }
    _topScrollView.pagingEnabled = YES;
    _topScrollView.showsHorizontalScrollIndicator =NO;
    _topScrollView.delegate = self;
    [_bgCollectionView addSubview:_topScrollView];
}

-(void)createPageControl:(NSArray *)smallScrollViewPag
{
    _pageControl = [[UIPageControl alloc] init];
    _pageControl.center = CGPointMake(Window_Width/2, InterfaceStyleOne_TopScrollView_Height-10);//?
    _pageControl.bounds = CGRectMake(0, 0, 100, 40);
    _pageControl.numberOfPages = smallScrollViewPag.count;
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    [_pageControl addTarget:self action:@selector(changePage) forControlEvents:UIControlEventValueChanged];
    [_bgCollectionView addSubview:_pageControl];
}

-(void)changePage
{
    _topScrollView.contentOffset = CGPointMake(_pageControl.currentPage*Window_Width, 0);
}

#pragma mark---scrollowView与pageControl的联合运用
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControl.currentPage = _topScrollView.contentOffset.x/Window_Width;
}

#pragma mark --- 创建定时器 使_topScrollView与_pageControl自动
-(void)createTimer:(int)time
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
-(void)onTimer
{
    static int speed = 1;
    _pageControl.currentPage +=speed;
    //建立两个变量的联系，这样能够简化逻辑，防止出错
    _topScrollView.contentOffset = CGPointMake(_pageControl.currentPage*Window_Width, 0);
//    NSLog(@"%d",_pageControl.currentPage);//查看当前页书
    if (_pageControl.currentPage == _array.count-1||_pageControl.currentPage==0)
    {
        speed = -speed;
    }
    
}
//当拖拽时，销毁定时器，避免图片切换过快
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (_timer != nil)
    {
        [_timer invalidate];
        _timer = nil;
    }
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_timer == nil)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    }
}
/*
-(void)goToBack
{
    
    //销毁定时器，不然就算页面消失，定时器依然存在
    if (_timer != nil)
    {
        [_timer invalidate];
        _timer = nil;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
 */

#pragma mark ---- 创建样式一 2.图标快捷键
-(void)createIcon:(NSArray *)array titKey:(NSString *)titKey imgKey:(NSString *)imgKey
{
    UIView * view = [[UIView alloc] init];
    view.frame = CGRectMake(0, InterfaceStyleOne_TopScrollView_Height, Window_Width, InterfaceStyleOne_IconView_Height);
    view.backgroundColor = [UIColor whiteColor];
    [_bgCollectionView addSubview:view];
    
    int imgWidth = (Window_Width-InterfaceStyleOne_IconImag_Spacing)/array.count;
    NSLog(@"%d",imgWidth);
    
    for (int i = 0; i < array.count;  i ++)
    {
        UIImageView * img =[[UIImageView alloc] init];
        img.frame = CGRectMake(InterfaceStyleOne_IconImag_Spacing+imgWidth*i, 10, imgWidth-InterfaceStyleOne_IconImag_Spacing+10, 40);
        img.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:array[i][imgKey]]]];
        [view addSubview:img];
        
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(InterfaceStyleOne_IconImag_Spacing+imgWidth*i, 55, imgWidth-InterfaceStyleOne_IconImag_Spacing+10, 15);
        label.text = array[i][titKey];
        [label setFont:[UIFont systemFontOfSize:12]];
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
    }
    /*
    int b = 30;
    int x = (self.view.frame.size.width-b)/5;
    NSLog(@"%d",x);
    
    for (int i = 0; i<array.count; i++)
    {
        UIImageView * img = [[UIImageView alloc] init];
        img.frame = CGRectMake(b+(x)*i, 50, x-b, 50);
        img.backgroundColor= [UIColor yellowColor];
        [self.view addSubview:img];
    }
     */
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
